<?php
class Category extends CI_Model
{
	function __construct()
	{
		parent::__construct();
	}
	function create($data)
	{
		$valid=$this->valid($data);
		if($valid!='ok') return $valid;
		if($this->db->insert('categories',$data)) 
			return array('content'	=> 'Create successful!',
					'type'		=> 'success',
			);

	}
	function get_sub_categories($id)
	{
		$this->db->select('*');
		$query = $this->db->get_where('categories',array('pid'	=> $id));
		return $query;
	}
	function update($data)
	{
		$valid=$this->valid($data);
		if($valid!='ok') return array('content'	=> $valid,
										'type'	=> 'error');
		if($this->db->update('categories',$data,array('id'=>$data['id'])))
		return array('content'	=> 'Update successful!',
					'type'		=> 'success',
		);
	}
	function delete($id)
	{
		$this->db->delete('categories',array('id'=>$id));
	}
	function get_category_info($id)
	{
		if($id==0) return array('id'	=> 0,
								'name'	=> $this->lang->line('HOME'),
								);
		$this->db->select('*');
		$query=$this->db->get_where('categories',array('id'=>$id));
		return $query->row_array();
	}
	function  get_category_path($id)
	{
		$category_path=array();
		if($id==0) return $category_path;
		$current_id=$id;
		$i=0;
		do
		{
			$category_path[$i]	= $this->get_category_info($current_id);
			$current_id=$category_path[$i]['pid'];
			$i++;
		}while($current_id!=0);
		return $category_path;
	}
	function valid($data)
	{
		if($data['name']=='')
			return 'Category \'s name is too short!';
		$this->db->select('*');
		if(isset($data['id']))
		{
			$query=$this->db->get_where('categories',array('id'=>$data['id']));
			if($query->num_rows==0)
				return 'Category ID is not valid!';
		}
		
		if($data['pid']==0) return 'ok';
		$query=$this->db->get_where('categories',array('id'=>$data['pid']));
		if($query->num_rows==0)
			return 'Parrent category is not valid!';
		return 'ok';
	}
} 
?>